﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Xml;
using Assist;
using Autodesk.Revit.DB;
using YArchitech.Controls;
using YArchitech.DataModel;
using YArchitech.LIB;
using YArchitech.LIB.YJKControls;
using YArchitech.Revit;

namespace YArchitech.HVAC
{
	public partial class FormLayValveElement : HYBaseForm
	{
		[DllImport("User32.dll")]
		private static extern int SendMessage(int Handle, int wMsg, int wParam, int lParam);

		public static void SetListViewSpacing(ListView lst, int x, int y)
		{
			FormLayValveElement.SendMessage(lst.Handle.ToInt32(), 4149, 0, x * 65536 + y);
		}

		public FormLayValveElement()
		{
			this.InitializeComponent();
			base.Icon = Resource.YArchitechIcon;
		}

		public FormLayValveElement(string valveType, Autodesk.Revit.DB.Document document, bool flag, string LayName)
		{
			this.InitializeComponent();
			base.Icon = Resource.YArchitechIcon;
			this.valveTypeName = valveType;
			this.doc = document;
			this.flag = flag;
			if (this.valveTypeName == "DuctValve")
			{
				this.Text = "风管阀件";
				this.hygrpList.Text = "风阀";
				this.tView = this.sfdr.GetAllNameAndImage2DByCategory("DuctValve", 0);
				this.dicValue = this.GetAscriptionInfo(0);
				this.tvwCurrPrj.Nodes.Add("风管附件");
				this.BingTvwFamilys(this.GetFamilys(BuiltInCategory.OST_DuctAccessory));
				this.BingRecordFamilys(this.GetFamilys(BuiltInCategory.OST_DuctAccessory));
			}
			else
			{
				this.Text = "水阀布置";
				this.hygrpList.Text = "水阀";
				this.tView = this.sfdr.GetAllNameAndImage2DByCategory("PipeValve", 0);
				this.dicValue = this.GetAscriptionInfo(1);
				this.tvwCurrPrj.Nodes.Add("管道附件");
				this.BingTvwFamilys(this.GetFamilys(BuiltInCategory.OST_PipeAccessory));
				this.BingRecordFamilys(this.GetFamilys(BuiltInCategory.OST_PipeAccessory));
				this.selectNoteName = LayName;
			}
			this.tv = this.tView;
		}

		private void BingRecordFamilys(List<Family> familys)
		{
			this.recordCurrPrjFamilyList.Nodes.Clear();
			foreach (Family family in familys)
			{
				TreeNode treeNode = new TreeNode(family.Name)
				{
					Tag = family
				};
				this.BingTvwFamilySymbol(treeNode, family);
				this.recordCurrPrjFamilyList.Nodes.Add(treeNode);
			}
		}

		private List<Family> GetFamilys(BuiltInCategory category)
		{
			IEnumerable<Element> enumerable = new FilteredElementCollector(this.doc).OfClass(typeof(Family)).ToElements();
			List<Family> list = new List<Family>();
			foreach (Element element in enumerable)
			{
				Family family = (Family)element;
                if (family.FamilyCategory.Id.IntegerValue == (int)category)
				{
					list.Add(family);
				}
			}
			return list;
		}

		private void BingTvwFamilys(List<Family> familys)
		{
			this.tvwCurrPrj.Nodes[0].Nodes.Clear();
			TreeNode treeNode = this.tvwCurrPrj.Nodes[0];
			foreach (Family family in familys)
			{
				TreeNode treeNode2 = new TreeNode(family.Name)
				{
					Tag = family
				};
				this.BingTvwFamilySymbol(treeNode2, family);
				treeNode.Nodes.Add(treeNode2);
			}
			this.tvwCurrPrj.SelectedNode = treeNode;
			this.tvwCurrPrj.ExpandAll();
		}

		private void BingTvwFamilySymbol(TreeNode tnFamily, Family family)
		{
			foreach (ElementId elementId in family.GetSymbolIds())
			{
				FamilySymbol familySymbol = this.doc.GetElement(elementId) as FamilySymbol;
				TreeNode node = new TreeNode(familySymbol.Name)
				{
					Tag = familySymbol
				};
				tnFamily.Nodes.Add(node);
			}
		}

		private void FormLayValveElement_Load(object sender, EventArgs e)
		{
			this.initcmbValveType();
			this.InitDetail();
			this.btnUp.Enabled = (this.pageIndex > 1);
			this.btnDown.Enabled = (this.totalPage > 1 && this.pageIndex < this.totalPage);
			this.ImportButtonImage();
		}

		private void initcmbValveType()
		{
			if ("DuctValve" == this.valveTypeName)
			{
				string[] ductcmbValveTypeText = this.userSetting.GetDuctcmbValveTypeText();
				string text = "";
				if (ductcmbValveTypeText[1] == "0" || ductcmbValveTypeText[1] == "")
				{
					this.tabHyControl.SelectedIndex = 0;
				}
				else
				{
					this.tabHyControl.SelectedIndex = 1;
				}
				text = ductcmbValveTypeText[0];
				foreach (KeyValuePair<string, List<string>> keyValuePair in this.dicValue)
				{
					this.cmbValveType.Items.Add(keyValuePair.Key);
					if (text == "")
					{
						text = keyValuePair.Key;
					}
					if (keyValuePair.Key == text)
					{
						this.typeValue = keyValuePair.Value;
					}
				}
				this.cmbValveType.Text = text;
				this.selectNoteName = ductcmbValveTypeText[2];
				return;
			}
			if ("PipeValve" == this.valveTypeName)
			{
				string[] pipecmbValveTypeText = this.userSetting.GetPipecmbValveTypeText();
				string text2 = "";
				if (pipecmbValveTypeText[1] == "0" || pipecmbValveTypeText[1] == "")
				{
					this.tabHyControl.SelectedIndex = 0;
				}
				else
				{
					this.tabHyControl.SelectedIndex = 1;
				}
				text2 = pipecmbValveTypeText[0];
				foreach (KeyValuePair<string, List<string>> keyValuePair2 in this.dicValue)
				{
					this.cmbValveType.Items.Add(keyValuePair2.Key);
					if (text2 == "")
					{
						text2 = keyValuePair2.Key;
					}
					if (keyValuePair2.Key == text2)
					{
						this.typeValue = keyValuePair2.Value;
					}
				}
				this.cmbValveType.Text = text2;
				if (this.selectNoteName == "")
				{
					this.selectNoteName = pipecmbValveTypeText[2];
				}
			}
		}

		private void initlsvDetail(int pageIndex, string keyword)
		{
			this.lsvDetail.Items.Clear();
			if (this.totalPage <= 0)
			{
				return;
			}
			if (keyword == "")
			{
				List<string> list = new List<string>();
				for (int i = 0; i < this.typeValue.Count; i++)
				{
					if (i < pageIndex * 16 && i >= (pageIndex - 1) * 16)
					{
						list.Add(this.typeValue[i]);
					}
				}
				using (List<string>.Enumerator enumerator = list.GetEnumerator())
				{
					while (enumerator.MoveNext())
					{
						string b = enumerator.Current;
						foreach (object obj in this.tv.Nodes)
						{
							TreeNode treeNode = (TreeNode)obj;
							if (treeNode.Tag is ListItem)
							{
								ListItem listItem = treeNode.Tag as ListItem;
								if (listItem.Name == b && listItem.Name.Contains(keyword))
								{
									this.lsvDetail.LargeImageList.Images.Add(listItem.Name, Image.FromFile(listItem.Value));
									ListViewItem listViewItem = new ListViewItem();
									listViewItem.Tag = listItem;
									listViewItem.ImageKey = listItem.Name;
									this.lsvDetail.Items.Add(listViewItem);
									FormLayValveElement.SetListViewSpacing(this.lsvDetail, this.lsvDetail.LargeImageList.ImageSize.Width, this.lsvDetail.LargeImageList.ImageSize.Height);
								}
							}
						}
					}
					goto IL_303;
				}
			}
			int num = 0;
			foreach (object obj2 in this.tv.Nodes)
			{
				TreeNode treeNode2 = (TreeNode)obj2;
				if (treeNode2.Tag is ListItem)
				{
					ListItem listItem2 = treeNode2.Tag as ListItem;
					if (this.typeValue.Contains(listItem2.Name) && listItem2.Name.Contains(keyword))
					{
						num++;
						if (num <= pageIndex * 16 && num > (pageIndex - 1) * 16)
						{
							this.lsvDetail.LargeImageList.Images.Add(listItem2.Name, Image.FromFile(listItem2.Value));
							ListViewItem listViewItem2 = new ListViewItem();
							listViewItem2.Tag = listItem2;
							listViewItem2.ImageKey = listItem2.Name;
							this.lsvDetail.Items.Add(listViewItem2);
							FormLayValveElement.SetListViewSpacing(this.lsvDetail, this.lsvDetail.LargeImageList.ImageSize.Width, this.lsvDetail.LargeImageList.ImageSize.Height);
						}
					}
				}
			}
			IL_303:
			foreach (object obj3 in this.lsvDetail.Items)
			{
				ListViewItem listViewItem3 = (ListViewItem)obj3;
				if (listViewItem3.ImageKey == this.selectNoteName)
				{
					this.lsvDetail.Select();
					this.lsvDetail.Focus();
					this.lsvDetail.FocusedItem = listViewItem3;
					this.lblValveName.Text = listViewItem3.ImageKey;
					this.lsvDetail.Items[listViewItem3.Index].Selected = true;
					this.lsvDetail.Items[listViewItem3.Index].EnsureVisible();
					break;
				}
			}
		}

		private void InitlsvDetail(string keyword)
		{
			this.lsvDetail.Items.Clear();
			if (this.totalPage <= 0)
			{
				return;
			}
			foreach (object obj in this.tv.Nodes)
			{
				TreeNode treeNode = (TreeNode)obj;
				if (treeNode.Tag is ListItem)
				{
					ListItem listItem = treeNode.Tag as ListItem;
					if (this.typeValue.Contains(listItem.Name) && listItem.Name.Contains(keyword))
					{
						this.lsvDetail.LargeImageList.Images.Add(listItem.Name, Image.FromFile(listItem.Value));
						ListViewItem listViewItem = new ListViewItem();
						listViewItem.Tag = listItem;
						listViewItem.ImageKey = listItem.Name;
						this.lsvDetail.Items.Add(listViewItem);
						FormLayValveElement.SetListViewSpacing(this.lsvDetail, this.lsvDetail.LargeImageList.ImageSize.Width, this.lsvDetail.LargeImageList.ImageSize.Height);
					}
				}
			}
		}

		private void InitDetail()
		{
			if (this.selectNoteName != "")
			{
				foreach (KeyValuePair<string, List<string>> keyValuePair in this.dicValue)
				{
					if (keyValuePair.Value.Contains(this.selectNoteName))
					{
						this.cmbValveType.Text = keyValuePair.Key;
						this.typeValue = keyValuePair.Value;
					}
				}
				for (int i = 0; i < this.typeValue.Count; i++)
				{
					if (this.typeValue[i] == this.selectNoteName)
					{
						this.pageIndex = (int)Math.Ceiling((double)(i + 1) / (double)this.pageNumber);
						this.totalPage = (int)Math.Ceiling((double)this.typeValue.Count / (double)this.pageNumber);
						this.btnUp.Enabled = (this.pageIndex > 1);
						this.btnDown.Enabled = (this.totalPage > 1 && this.pageIndex < this.totalPage);
						this.ImportButtonImage();
						break;
					}
				}
				this.initlsvDetail(this.pageIndex, "");
				return;
			}
			this.initlsvDetail(this.pageIndex, "");
		}

		private Dictionary<string, List<string>> GetAscriptionInfo(int type)
		{
			Dictionary<string, List<string>> dictionary = new Dictionary<string, List<string>>();
			XmlDocument xmlDoc = XMLOperating.LoadXml(Path.Combine(Product.DataLocation, "DuctPipeValue.xml"));
			new List<string>();
			foreach (object obj in XMLOperating.GetXmlNodeByAttribute(xmlDoc, "DuctPipevalues", "type", type.ToString()).ChildNodes)
			{
				XmlNode xmlNode = (XmlNode)obj;
				string attribute = (xmlNode as XmlElement).GetAttribute("class");
				List<string> value = (xmlNode as XmlElement).GetAttribute("values").Split(new char[]
				{
					','
				}).ToList<string>();
				dictionary.Add(attribute, value);
			}
			return dictionary;
		}

		private void lsvDetail_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			ListItem listItem = this.lsvDetail.HitTest(e.X, e.Y).Item.Tag as ListItem;
			this.ButtonOk(listItem.Tag.ToString());
		}

		private void ButtonOk(string Tag = "")
		{
			this.UserSettingWrite();
			try
			{
				this.FamilyLoad(Tag);
				base.DialogResult = DialogResult.OK;
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message, "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
			}
		}

		private void UserSettingWrite()
		{
			try
			{
				string[] array = new string[]
				{
					"",
					"",
					""
				};
				array[0] = this.cmbValveType.Text;
				if (this.tabHyControl.SelectedIndex == 0)
				{
					array[1] = "0";
				}
				else
				{
					array[1] = "1";
				}
				if (this.lsvDetail.SelectedItems.Count == 0)
				{
					array[2] = "";
				}
				else
				{
					array[2] = this.lsvDetail.SelectedItems[0].ImageKey;
				}
				if ("DuctValve" == this.valveTypeName)
				{
					this.userSetting.WriteDuctcmbValveTypeText(array);
				}
				else if ("PipeValve" == this.valveTypeName)
				{
					this.userSetting.WritePipecmbValveTypeText(array);
				}
			}
			catch (Exception)
			{
			}
		}

		public static TreeNode GetSelectedNode(TreeView tv, string name)
		{
			TreeNode treeNode = null;
			foreach (object obj in tv.Nodes)
			{
				TreeNode treeNode2 = (TreeNode)obj;
				if (treeNode2 != null)
				{
					treeNode = FormLayValveElement.GetSelectedNode(treeNode2, name);
					if (treeNode != null)
					{
						break;
					}
				}
			}
			return treeNode;
		}

		public static TreeNode GetSelectedNode(TreeNode tn, string name)
		{
			TreeNode treeNode = null;
			if (tn != null)
			{
				if (tn.Text == name && tn.GetNodeCount(true) == 0)
				{
					return tn;
				}
				foreach (object obj in tn.Nodes)
				{
					TreeNode treeNode2 = (TreeNode)obj;
					if (treeNode2.Text == name)
					{
						treeNode = treeNode2;
						break;
					}
					treeNode = FormLayValveElement.GetSelectedNode(treeNode2, name);
					if (treeNode != null)
					{
						break;
					}
				}
			}
			return treeNode;
		}

		private void lsvDetail_ItemMouseHover(object sender, ListViewItemMouseHoverEventArgs e)
		{
			this.lsvDetail.Focus();
			this.lsvDetail.FocusedItem = e.Item;
			this.lsvDetail.Items[e.Item.Index].Selected = true;
			this.lblValveName.Text = e.Item.ImageKey;
			this.lsvDetail.Items[e.Item.Index].EnsureVisible();
			TreeNode selectedNode = FormLayValveElement.GetSelectedNode(this.tv, this.lblValveName.Text);
			this.tv.SelectedNode = selectedNode;
		}

		private void FamilyLoad(string Tag = "")
		{
			if (this.tabHyControl.SelectedIndex == 0)
			{
				this.GetYArchitechFamily(Tag);
				return;
			}
			this.GetCurrPrjFamily();
		}

		private void GetYArchitechFamily(string Tag = "")
		{
			try
			{
				if (this.valveTypeName == "DuctValve")
				{
					this.fs = this.sfdr.GetFamilySymbolById(Convert.ToInt32(Tag), "DuctValve", this.doc, BuiltInCategory.OST_DuctAccessory);
				}
				else if (this.flag)
				{
					SubTransaction subTran = null;
					int id = Convert.ToInt32(Tag);
					this.fs = this.sfdr.GetFamilySymbolByFamilyId(id, "PipeValve", this.doc, subTran, (Autodesk.Revit.DB.BuiltInCategory)(-2008055));
				}
				else
				{
					int id2 = Convert.ToInt32(Tag);
					this.fs = this.sfdr.GetFamilySymbolById(id2, "PipeValve", this.doc, BuiltInCategory.OST_PipeAccessory);
				}
				if (this.fs == null)
				{
					throw new Exception("加载族失败");
				}
			}
			catch (Exception ex)
			{
				ex.ToString();
				MessageBox.Show("读取族库失败", "盈建科提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
			}
		}

		private void GetCurrPrjFamily()
		{
			if (this.tvwCurrPrj.SelectedNode.Level == 2)
			{
				this.fs = (this.tvwCurrPrj.SelectedNode.Tag as FamilySymbol);
				return;
			}
			if (this.tvwCurrPrj.SelectedNode.Level == 1)
			{
				this.fs = (this.tvwCurrPrj.SelectedNode.Nodes[0].Tag as FamilySymbol);
			}
		}

		private void cmbValveType_SelectedIndexChanged(object sender, EventArgs e)
		{
			foreach (KeyValuePair<string, List<string>> keyValuePair in this.dicValue)
			{
				if (keyValuePair.Key == this.cmbValveType.Text)
				{
					this.typeValue = keyValuePair.Value;
				}
			}
			this.txtValveSearch.Text = "";
			this.pageIndex = 1;
			this.totalPage = this.GetTotalPage("");
			this.initlsvDetail(this.pageIndex, "");
			this.btnUp.Enabled = (this.pageIndex > 1);
			this.btnDown.Enabled = (this.totalPage > 1 && this.pageIndex < this.totalPage);
			this.ImportButtonImage();
		}

		private void tvwCurrPrj_AfterSelect(object sender, TreeViewEventArgs e)
		{
			this.tvwCurrPrj.SelectedNode.BackColor = System.Drawing.Color.DodgerBlue;
			this.tvwCurrPrj.SelectedNode.ForeColor = System.Drawing.Color.White;
		}

		private void tvwCurrPrj_BeforeSelect(object sender, TreeViewCancelEventArgs e)
		{
			if (this.tvwCurrPrj.SelectedNode != null)
			{
				this.tvwCurrPrj.SelectedNode.BackColor = System.Drawing.Color.White;
				this.tvwCurrPrj.SelectedNode.ForeColor = System.Drawing.Color.Black;
			}
		}

		private void tvwCurrPrj_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
		{
			if (e.Node.Level != 2)
			{
				return;
			}
			this.ButtonOk("");
		}

		private void FormLayValveElement_FormClosing(object sender, FormClosingEventArgs e)
		{
			this.UserSettingWrite();
		}

		private void txtValveSearch_TextChanged(object sender, EventArgs e)
		{
			string keyword = this.txtValveSearch.Text.Trim();
			this.pageIndex = 1;
			this.totalPage = this.GetTotalPage(keyword);
			this.initlsvDetail(this.pageIndex, keyword);
			this.btnUp.Enabled = (this.pageIndex > 1);
			this.btnDown.Enabled = (this.totalPage > 1 && this.pageIndex < this.totalPage);
			this.ImportButtonImage();
		}

		private void btnUp_Click(object sender, EventArgs e)
		{
			if (this.pageIndex > 0)
			{
				this.pageIndex--;
				this.initlsvDetail(this.pageIndex, this.txtValveSearch.Text.Trim());
				this.btnUp.Enabled = (this.pageIndex > 1);
				this.btnDown.Enabled = (this.totalPage > 1 && this.pageIndex < this.totalPage);
				this.ImportButtonImage();
			}
		}

		private void btnDown_Click(object sender, EventArgs e)
		{
			if (this.pageIndex < this.totalPage)
			{
				this.pageIndex++;
				this.initlsvDetail(this.pageIndex, this.txtValveSearch.Text.Trim());
				this.btnUp.Enabled = (this.pageIndex > 1);
				this.btnDown.Enabled = (this.totalPage > 1 && this.pageIndex < this.totalPage);
				this.ImportButtonImage();
			}
		}

		private void SelectedCurrentValve()
		{
		}

		private int GetTotalPage(string keyword = "")
		{
			int result = 0;
			if (this.typeValue == null || this.typeValue.Count <= 0)
			{
				return result;
			}
			IList<string> list;
			if (string.IsNullOrEmpty(keyword))
			{
				list = this.typeValue;
			}
			else
			{
				list = (from x in this.typeValue
				where x.Contains(keyword)
				select x).ToList<string>();
			}
			return (int)Math.Ceiling((double)list.Count / (double)this.pageNumber);
		}

		private void searchInCurProject_TextChanged(object sender, EventArgs e)
		{
			string keyword = this.searchInCurProject.Text.Trim();
			List<Family> familys;
			if ("DuctValve" == this.valveTypeName)
			{
				familys = this.GetFamilys(BuiltInCategory.OST_DuctAccessory);
			}
			else
			{
				familys = this.GetFamilys(BuiltInCategory.OST_PipeAccessory);
			}
			List<Family> familys2 = (from x in familys
			where x.Name.Contains(keyword)
			select x).ToList<Family>();
			this.BingTvwFamilys(familys2);
		}

		private void label2_Click(object sender, EventArgs e)
		{
		}

		private void ImportButtonImage()
		{
			string filename = Path.Combine(Product.ResLocation, "ValveUp.png");
			string filename2 = Path.Combine(Product.ResLocation, "ValveDown.png");
			string filename3 = Path.Combine(Product.ResLocation, "ValveUpGray.png");
			string filename4 = Path.Combine(Product.ResLocation, "ValveDownGray.png");
			if (this.btnUp.Enabled)
			{
				this.btnUp.BackgroundImage = Image.FromFile(filename);
			}
			else
			{
				this.btnUp.BackgroundImage = Image.FromFile(filename3);
			}
			if (this.btnDown.Enabled)
			{
				this.btnDown.BackgroundImage = Image.FromFile(filename2);
				return;
			}
			this.btnDown.BackgroundImage = Image.FromFile(filename4);
		}

		public FamilySymbol fs;

		private Document doc;

		private TreeView tv;

		private string valveTypeName = "DuctValve";

		private TreeView tView;

		private Dictionary<string, List<string>> dicValue = new Dictionary<string, List<string>>();

		private List<string> typeValue = new List<string>();

		private int pageIndex = 1;

		private int totalPage;

		private int pageNumber = 16;

		private SpaceFamilyDataReader sfdr = new SpaceFamilyDataReader();

		private HVACUserSetting userSetting = new HVACUserSetting();

		private TreeView recordCurrPrjFamilyList = new TreeView();

		private bool flag;

		private string selectNoteName = "";

		private const int LVM_FIRST = 4096;

		private const int LVM_SETICONSPACING = 4149;
	}
}
